package org.elephas.service;

import java.util.List;

import org.apache.wicket.util.string.Strings;
import org.elephas.model.Blog;
import org.elephas.model.BlogMembership;
import org.elephas.model.User;
import org.elephas.persistence.Dao;
import org.elephas.persistence.query.QueryParam;
import org.hibernate.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author Gerolf Seitz
 * 
 */
@Service
public class UserFinder {

	@Autowired
	private Dao dao;

	/**
	 * Loads the {@link User} with the specified email address;
	 * 
	 * @param email
	 *            the user's email address
	 * @return the user or null in case there is no user with the given email
	 *         address
	 */
	public User findByEmail(String email) {
		if (Strings.isEmpty(email)) {
			return null;
		}
		Query query = dao
				.createQuery("select u from User u where u.emailAddress = :email");
		query.setString("email", email);
		return (User) query.uniqueResult();
	}

	/**
	 * @param param
	 * @return
	 */
	public List<User> findUsers(QueryParam param) {
		String hql = "select user from User user";
		return dao.createQuery(hql, param).list();
	}

	/**
	 * Calculates the number of {@link User}s.
	 * 
	 * @return the number of {@link Blog}s
	 */
	public int countUsers() {
		Long count = (Long) dao
				.createQuery("select count(user) from User user")
				.uniqueResult();
		return count.intValue();
	}

	/**
	 * @param param
	 * @return
	 */
	public List<BlogMembership> findMemberships(QueryParam param) {
		String hql = "select ms from BlogMembership ms";
		return dao.createQuery(hql, param).list();
	}

	/**
	 * Calculates the number of {@link BlogMembership}s.
	 * 
	 * @return the number of {@link BlogMembership}s.
	 */
	public int countMemberships() {
		Long count = (Long) dao.createQuery(
				"select count(ms) from BlogMembership ms").uniqueResult();
		return count.intValue();
	}

	/**
	 * Loads a {@link BlogMembership} with the given id.
	 * 
	 * @param id
	 *            the {@link BlogMembership}'s id
	 * @return the {@link BlogMembership} with the given id or null if no such
	 *         {@link BlogMembership} exists
	 */
	public BlogMembership findMembershipByUuid(String id) {
		return (BlogMembership) dao.get(BlogMembership.class, id);
	}
}
